<?php

class page {

    public function __construct() {
        $this->network = & $GLOBALS['network'];
        $this->user = & $GLOBALS['user'];
        $this->cache = & $GLOBALS['cache'];
        $this->logger= & $GLOBALS['logger'];
        $this->db1 = & $GLOBALS['db1'];
        $this->db2 = & $GLOBALS['db2'];
        $this->request = array(); //存储客户的请求数组
        $this->params = new stdClass; //存储客户请求中所带的参数
        $this->params->user = FALSE; //参数表中的用户
        $this->params->group = FALSE; //参数表中的组
        $this->title = NULL; //标题
        $this->html = NULL; //网页内容
        $this->controllers = $GLOBALS['C']->INCPATH . 'controllers/'; //控制器的实际路径
        $this->lang_data = array(); //语言数据
        $this->tpl_name = 'default'; //主题模板名称
    }

    public function LOAD() {
        $this->_parse_input(); //解析输入,即根据请求串分析实际访问的功能

        if (!$this->user->is_logged && $this->param('invited')) {
            $_SESSION['invite_code'] = trim($this->param('invited'));
        }


        $this->logger->debug("This is in class_page.php_".($this->request[0]=='home'));


      if (!(($this->request[0]=='home'||$this->request[0]=='signin'))&&!$this->user->is_logged) {
           $this->redirect('home');
      }

        $this->_set_template();
        $this->_send_headers();
        $this->_load_controller();

    }

    private function _parse_input() {
        global $C;
        $this->params->user = FALSE;
        $this->params->group = FALSE;
        $request = $_SERVER['REQUEST_URI']; //请求的服务器路径,类似:/guweibo/index.php?XDEBUG_SESSION_START=netbeans-xdebug
        $pos = strpos($request, '?'); //定位查询参数起始位置
        if (FALSE !== $pos) {//如果存在查询参数,则取request为查询参数之前的所有字符形成请求串
            $request = substr($request, 0, $pos);
        }
        if (FALSE !== strpos($request, '//')) {//如果在request中能找到两个斜杠,则将两个斜杠变为一个
            $request = preg_replace('/\/+/iu', '/', $request);
        }
        $tmp = str_replace(array('http://', 'https://'), '', $C->SITE_URL); //去掉站点url中包含的http或者https
        if (FALSE !== strpos($tmp, '//')) {
            $tmp = preg_replace('/\/+/iu', '/', $tmp); //去掉多余的/
        }
        $tmp = substr($tmp, strpos($tmp, '/')); //取站点url/后面的内容.
        if (substr($request, 0, strlen($tmp)) == $tmp) {//取得所主求的实际程序名称,如index.php
            $request = substr($request, strlen($tmp));
        }
        $is_mobile = FALSE;
        $request = '/' . ltrim($request); //变成/index.php
        if (substr($_SERVER['HTTP_HOST'], 0, 2) == 'm.') {//如果服务器主机域名形如m.xxxx.com,则说明是使用移动客户端访问
            $is_mobile = TRUE;
            $tmp = substr($_SERVER['HTTP_HOST'], 2);
            $C->DOMAIN = 'm.' . $C->DOMAIN;
            $C->SITE_URL = preg_replace('/^(http(s)?\:\/\/)(.*)$/iu', '$1m.$3', $C->SITE_URL);
            $C->API_ID = 1;
        } elseif ($request == '/m' || substr($request, 0, 3) == '/m/') {//如果请求形如www.xxx.com/m/,则也是移动客户端访问
            $is_mobile = TRUE;
            $C->SITE_URL .= 'm/';
            $C->API_ID = 1;
        }
        if ($is_mobile) {//如果是移动客户端的话
            $is_touch = FALSE; //获取是否为触摸屏信息
            if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')) {//如果客户浏览器是iPhone
                $is_touch = TRUE;
            } elseif (isset($_COOKIE['mobitouch']) && $_COOKIE['mobitouch'] == 1) {//如果cookie记录了是触摸屏手机
                $is_touch = TRUE;
            }
            if ($is_touch) {
                $this->controllers .= 'mobile_iphone/'; //
            } else {
                $this->controllers .= 'mobile/';
            }
        }
        if ($_SERVER['HTTP_HOST'] != $C->DOMAIN && FALSE !== strpos($_SERVER['HTTP_HOST'], '.' . $C->DOMAIN)) {//如果主机名称不是配置的域并且主机名称
            $tmp = str_replace('.' . $C->DOMAIN, '', $_SERVER['HTTP_HOST']);
            $tmp = preg_replace('/^www\./', '', $tmp);
            $tmp = trim($tmp);
            if (!empty($tmp)) {
                $request = $tmp . '/' . $request;
            }
        }
        $request = trim($request, '/');
        if (empty($request)) {
            $this->request[] = 'home';
            return;
        }
        if (substr($request, 0, 2) == 'm/') {
            $request = substr($request, 2);
        }
        $request = explode('/', $request); //最后形成的$request变量是由/斜杠连接而成的请求
        foreach ($request as $i => $one) {
            if (FALSE !== strpos($one, ':') && preg_match('/^([a-z0-9\-_\x{4e00}-\x{9fa5}]+)\:(.*)$/iu', urldecode($one), $m)) {//如果形如:user:12模式,则需要将参数的值与字段分离
                $this->params->{$m[1]} = $m[2];
                unset($request[$i]); //销毁之
                continue;
            }
            $one_tmp = urldecode($one);
            if (!preg_match('/^([a-z0-9\-\._\x{4e00}-\x{9fa5}]+)$/iu', $one_tmp)) {//如果没有参数需要分离,则继续
                unset($request[$i]);
                continue;
            }
        }
        $request = array_values($request);
        if (0 == count($request)) {//如果request不包含请求,则将请求设为对首页的请求
            $this->request[] = 'home';
            return;
        }
        if ($request[0] == 'oauth' || $request[0] == '1') {//如果使用api方式调用,则将控制器路径设为oauth目录下面的控制器
            $this->controllers = $GLOBALS['C']->INCPATH . 'controllers/api/';
            if ($request[0] == 'oauth') {
                $this->controllers .= 'oauth/';
            }
            unset($request[0]);
            foreach ($request as &$v) {
                if (preg_match('/\.(xml|json|rss|atom)$/iu', $v, $m)) {
                    $v = str_ireplace('.' . $m[1], '', $v);
                    $this->params->format = strtolower($m[1]);
                }
            }
            $request = array_values($request);
            foreach ($request as $i => $one) {
                $t = $this->request;
                $t[] = $one;
                if (file_exists($this->controllers . implode('_', $t) . '.php')) {
                    $this->request[] = $one;
                    unset($request[$i]);
                    continue;
                }
                break;
            }
            $request = array_values($request);
            if (0 == count($this->request)) {
                $this->request[] = 'home';
            }
            $this->params->more = $request;
            return;
        }
        $first = urldecode($request[0]);
        if (file_exists($this->controllers . $first . '.php')) {//查看控制器中是否存在请求对应的文件.
            $this->request[] = $first;
        } elseif ($u = $this->network->get_user_by_username($first, FALSE, TRUE)) {
            $this->request[] = 'user';
            $this->params->user = $u;
        } elseif ($g = $this->network->get_group_by_name($first, FALSE, TRUE)) {
            $this->request[] = 'group';
            $this->params->group = $g;
        } elseif (substr($first, 0, 1) == '$') {

            if ($s = $this->network->get_stock_by_stockname(substr($first, 1))) {
                $this->request[] = 'stock';
                $this->params->stock = $s;
            } elseif ($s = $this->network->get_stock_by_stockcode(substr($first, 1))) {
                $this->request[] = 'stock';
                $this->params->stock = $s;
            }
        } else {
            $this->request[] = 'home';
            return;
        }
        unset($request[0]);
        foreach ($request as $one) {
            $t = $this->request;
            $t[] = $one;
            if (file_exists($this->controllers . implode('_', $t) . '.php')) {
                $this->request[] = $one;
                continue;
            }
            break;
        }
        if (!$this->params->user) {
            $this->params->user = $this->user->is_logged ? $this->user->id : FALSE;
        }
        if (0 == count($this->request)) {
            $this->request[] = 'home';
            return;
        }
    }

    private function _send_headers() {//根据不同的请求类型设置头
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Cache-Control: post-check=0, pre-check=0', FALSE);
        header('Pragma: no-cache');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');

        if ($this->request[0] == 'ajax') {
            if ($this->param('ajaxtp') == 'xml') {
                header('Content-type: application/xml; charset=utf-8');
            } else {
                header('Content-type: text/plain; charset=utf-8');
            }
        } else {
            header('Content-type: text/html; charset=utf-8');
        }
    }

    public function _set_template() {//设置模板
        if (isset($GLOBALS['C']->THEME) && file_exists($GLOBALS['C']->INCPATH . '../themes/' . $GLOBALS['C']->THEME . '/theme.php')) {
            $this->tpl_name = $GLOBALS['C']->THEME;
        }
        $this->tpl_dir = $GLOBALS['C']->INCPATH . '../themes/' . $this->tpl_name . '/';
        $current_theme = FALSE;
        @include( $this->tpl_dir . 'theme.php' );
        $GLOBALS['C']->LOGO_HEIGHT = 0;
        if ($current_theme && isset($current_theme->logo_height)) {
            $GLOBALS['C']->LOGO_HEIGHT = intval($current_theme->logo_height);
        }
        $GLOBALS['C']->THEME = $this->tpl_name;
        return $current_theme;
    }

    private function _load_controller() {//加载控制器
        global $C, $D;
        $D = new stdClass;
        $D->page_title = $C->SITE_TITLE;
        $db1 = & $this->db1;
        $db2 = & $this->db2;
        $db = & $db2;
        $cache = & $this->cache;
        $user = & $this->user;
        $network = & $this->network;

        require_once( $this->controllers . implode('_', $this->request) . '.php' );
    }

    public function load_template($filename, $output_content=TRUE) {
        global $C, $D;
        $filename = $this->tpl_dir . 'html/' . $filename;
        if ($output_content) {
            require($filename);
            return TRUE;
        } else {
            ob_start();
            require($filename);
            $cnt = ob_get_contents();
            ob_end_clean();
            return $cnt;
        }
    }

    public function load_langfile($filename) {//加载语言文件,即将语言文件中的文字加载至数组lang_data中
        if (!isset($this->tmp_loaded_langfiles)) {
            $this->tmp_loaded_langfiles = array();
        }
        $this->tmp_loaded_langfiles[] = $filename;
        global $C;
        $lang = array();
        ob_start();
        require( $GLOBALS['C']->INCPATH . 'languages/' . $GLOBALS['C']->LANGUAGE . '/' . $filename );
        ob_end_clean();
        if (!is_array($lang)) {
            return FALSE;
        }
        foreach ($lang as $k => $v) {
            $this->lang_data[$k] = $v;
        }
    }

    public function lang($key, $replace_strings=array(), $in_another_language=FALSE) {
        if ($in_another_language && $in_another_language != $GLOBALS['C']->LANGUAGE && is_dir($GLOBALS['C']->INCPATH . 'languages/' . $in_another_language)) {
            return $this->lang_in_another_language($key, $replace_strings, $in_another_language);
        }
        if (empty($key)) {//如果key为空,则直接返回空字符串
            return '';
        }
        if (!isset($this->lang_data[$key])) {//如果在语言数据数组中不包含指定的key的值,则返回空字符串
            return '';
        }
        $txt = $this->lang_data[$key]; //将key对应的语言翻译放入$txt
        if (0 == count($replace_strings)) {//如果替代字符串数组不包含元素,则直接返回语言数据数组
            return $txt;
        }
        return str_replace(array_keys($replace_strings), array_values($replace_strings), $txt); //其它情况则在$txt中将指定key对应的值替换
    }

    public function lang_in_another_language($key, $replace_strings=array(), $in_language=FALSE) {//在指定的语言中将key对应的文本替换成另一个字符串
        if (empty($key)) {
            return '';
        }
        if (!isset($this->tmp_loaded_langfiles)) {
            return '';
        }
        $lang_data = array();
        foreach ($this->lang_data as $k => $v) {
            $lang_data[$k] = $v;
        }
        if ($in_language && is_dir($GLOBALS['C']->INCPATH . 'languages/' . $in_language)) {//从指定的语言中加载语言文本
            foreach ($this->tmp_loaded_langfiles as $f) {//加载过的语言文件数组
                $lang = array();
                ob_start();
                require( $GLOBALS['C']->INCPATH . 'languages/' . $in_language . '/' . $f );
                ob_end_clean();
                if (is_array($lang)) {
                    foreach ($lang as $k => $v) {
                        $lang_data[$k] = $v; //将获取的语言文本放入$lang_data
                    }
                }
            }
        }
        if (!isset($lang_data[$key])) {
            return '';
        }
        $txt = $lang_data[$key]; // 查找指定key对应的翻译
        if (0 == count($replace_strings)) {//如果没有要另一种语言的翻译进行替换的字符串
            return $txt;
        }
        return str_replace(array_keys($replace_strings), array_values($replace_strings), $txt); //在$txt中查找符合的字符串并进行替换,是在翻译的文本中进行替换
    }

    public function param($key) {//根据指定的key获取参数的值,并转换成数值或者逻辑值
        if (FALSE == isset($this->params->$key)) {//如果没有设置key对应的值,则直接返回逻辑值FALSE
            return FALSE;
        }
        $value = $this->params->$key;
        if (is_numeric($value)) {
            return floatval($value);
        }
        if ($value == "true" || $value == "TRUE") {
            return TRUE;
        }
        if ($value == "false" || $value == "FALSE") {
            return FALSE;
        }
        return $value;
    }

    public function redirect($loc, $abs=FALSE) {
        global $C;
        if (!$abs && preg_match('/^http(s)?\:\/\//', $loc)) {
            $abs = TRUE;
        }
        if (!$abs) {
            if ($loc{0} != '/') {
                $loc = $C->SITE_URL . $loc;
            }
        }
        if (!headers_sent()) {
            header('Location: ' . $loc);
        }
        echo '<meta http-equiv="refresh" content="0;url=' . $loc . '" />';
        echo '<script type="text/javascript"> self.location = "' . $loc . '"; </script>';
        exit;
    }

    public function set_lasturl($url='') {
        if (!empty($url)) {
            $_SESSION['LAST_URL'] = $url;
        } else {
            $_SESSION['LAST_URL'] = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $_SERVER['REQUEST_URI'];
        }
        $_SESSION['LAST_URL'] = rtrim($_SESSION['LAST_URL'], '/');
    }

    public function get_lasturl() {
        return isset($_SESSION['LAST_URL']) ? $_SESSION['LAST_URL'] : '/';
    }

}

?>